import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../core/history.dart';
import '../core/theme_config.dart';
import 'player_page.dart';

class HistoryPage extends StatefulWidget {
  const HistoryPage({super.key});

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  List<PlayHistoryItem> _items = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    final list = await HistoryStore.load();
    setState(() {
      _items = list;
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    // 使用可用区域宽度而不是整屏宽度，以适配个人中心右侧内容区
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('播放历史'),
        toolbarHeight: 32,
        centerTitle:  false,
        backgroundColor: themeConfig.currentGradient.colors.first,
        automaticallyImplyLeading: false, // 不显示返回按钮
        //字体颜色
        titleTextStyle: TextStyle(fontSize: 18,color: themeConfig.currentTextColor),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_outline_rounded),
            onPressed: () async {
              await HistoryStore.clear();
              await _load();
            },
          )
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: themeConfig.currentGradient,
        ),
        child: _loading
            ? const Center(child: CircularProgressIndicator())
            : _items.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.history, size: 64, color: themeConfig.currentTextColor.withOpacity(0.5)),
                        SizedBox(height: 16),
                        Text('暂无历史记录', style: TextStyle(fontSize: 16, color: themeConfig.currentTextColor)),
                      ],
                    ),
                  )
                : LayoutBuilder(
                    builder: (context, constraints) {
                      final width = constraints.maxWidth;
                      // 根据可用宽度动态计算列数，保证窄屏下至少两列并避免内容溢出
                      final crossAxisCount = width >= 1200
                          ? 8
                          : width >= 900
                              ? 6
                              : width >= 600
                                  ? 4
                                  : width >= 420
                                      ? 3
                                      : 2;
                      // 调整纵横比：越窄越高，给文本区域更多空间
                      final ratio = width < 380
                          ? 0.54
                          : width < 600
                              ? 0.6
                              : 0.66;

                      return GridView.builder(
                        padding: const EdgeInsets.all(16),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: crossAxisCount,
                          crossAxisSpacing: 12,
                          mainAxisSpacing: 12,
                          childAspectRatio: ratio,
                        ),
                        itemCount: _items.length,
                        itemBuilder: (context, index) {
                          final item = _items[index];
                          return Dismissible(
                            key: ValueKey(item.url.isNotEmpty ? item.url : '${item.title}-$index'),
                            direction: DismissDirection.endToStart,
                            background: Container(
                              alignment: Alignment.centerRight,
                              padding: const EdgeInsets.only(right: 16),
                              decoration: BoxDecoration(
                                color: Colors.red.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: const Icon(Icons.delete, color: Colors.red),
                            ),
                            onDismissed: (_) async {
                              await _deleteItem(item);
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(content: Text('已删除一条历史记录')),
                              );
                            },
                            child: _buildHistoryCard(item, context, themeConfig),
                          );
                        },
                      );
                    },
                  ),
      ),
    );
  }

  Future<void> _deleteItem(PlayHistoryItem item) async {
    await HistoryStore.deleteByUrl(item.url);
    setState(() {
      _items.removeWhere((e) => e.url == item.url);
    });
  }

  Widget _buildHistoryCard(PlayHistoryItem item, BuildContext context, ThemeConfig themeConfig) {
    return Stack(
      children: [
        Card(
          elevation: 2,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => PlayerPage(
                    name: item.name,
                  title: item.title,
                  url: item.url,
                  cover: item.cover,
                  sourceSite: item.sourceSite,
                ),
                ),
              );
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // 封面图片
                Expanded(
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                    child: item.cover == null || item.cover!.isEmpty
                        ? Container(
                            color: Colors.grey[200],
                            child: const Center(
                              child: Icon(Icons.movie, size: 40, color: Colors.grey),
                            ),
                          )
                        : CachedNetworkImage(
                            imageUrl: item.cover!,
                            fit: BoxFit.cover,
                            httpHeaders: const {
                              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                              'Referer': 'https://movie.douban.com/',
                            },
                            placeholder: (context, url) => Container(
                              color: Colors.grey[200],
                              child: const Center(child: CircularProgressIndicator(strokeWidth: 2)),
                            ),
                            errorWidget: (context, url, error) => Container(
                              color: Colors.grey[200],
                              child: const Center(child: Icon(Icons.movie, color: Colors.grey)),
                            ),
                          ),
                  ),
                ),
                // 内容信息
                Padding(
                  padding: const EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        item.title,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                          color: themeConfig.currentTextColor,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      if (item.sourceSite != null)
                        Text(
                          item.sourceSite!,
                          style: TextStyle(
                            fontSize: 12,
                            color: themeConfig.currentTextColor.withOpacity(0.7),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        )
                      else if (item.siteName != null)
                        Text(
                          item.siteName!,
                          style: TextStyle(
                            fontSize: 12,
                            color: themeConfig.currentTextColor.withOpacity(0.7),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      const SizedBox(height: 4),
                      Text(
                        _formatDate(item.time),
                        style: TextStyle(
                          fontSize: 12,
                          color: themeConfig.currentTextColor.withOpacity(0.6),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        // 右上角删除按钮
        Positioned(
          top: 6,
          right: 6,
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(16),
              onTap: () async {
                await _deleteItem(item);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('已删除一条历史记录')),
                );
              },
              child: Container(
                padding: const EdgeInsets.all(4),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: const Icon(Icons.close, size: 16, color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  String _formatDate(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays > 365) {
      return '${difference.inDays ~/ 365}年前';
    } else if (difference.inDays > 30) {
      return '${difference.inDays ~/ 30}个月前';
    } else if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}